package com.lmind.core.gps.publish;

import java.util.concurrent.ConcurrentHashMap;

import com.lmind.core.gps.terminal.Terminal;
import com.lmind.core.gps.terminal.message.AbstractMessage;
import com.lmind.core.gps.tm.TerminalManager;
import com.lmind.core.gps.tm.TerminalManagerListener;
import com.lmind.core.publish.AbstractPublisher;
import com.lmind.core.publish.Publisher;
import com.lmind.core.publish.SubscribeException;
import com.lmind.core.publish.Subscriber;

/**
 * 终端消息发布者
 * 1.对外发布终端的状态及消息
 * @author 刘勉
 *
 */
public class DefaultTerminalPublisher extends AbstractPublisher<GpsPub> implements Publisher<GpsPub> {
	
	private TerminalManager terminalManager;
	
	private TMListener listener = new TMListener();
	
	public void setTerminalManager(TerminalManager terminalManager) {
		if (this.terminalManager != null)
			this.terminalManager.removeTerminalManagerListener(listener);
		this.terminalManager = terminalManager;
		if (this.terminalManager != null)
			this.terminalManager.addTerminalManagerListener(listener);
	}

	@Override
	public void subscribe(Subscriber<GpsPub> subscriber, String name) throws SubscribeException {
		doSubscribe(subscriber, name);
	}
	
	@Override
	public void unsubscribe(Subscriber<GpsPub> subscriber, String name) throws SubscribeException {
		doUnsubscribe(subscriber, name);
	}

	@Override
	public void cleanSubscribe(Subscriber<GpsPub> subscriber) throws SubscribeException {
		doCleanSubscribe(subscriber);
	}

	class TMListener implements TerminalManagerListener {
		@Override
		public void message(Terminal terminal, AbstractMessage message) {
			GpsPub pub = new GpsPub(terminal, message);
			ConcurrentHashMap<Subscriber<GpsPub>,String> set = subscribers.get(terminal.getGroup());
			if (set == null)
				return;
			for (Subscriber<GpsPub> subscriber : set.keySet()) {
				subscriber.feed(set.get(subscriber), pub);
			}
		}
	}
}
